import { moveToCenterByLonAndLat, transformLonlatToNow, getRadius } from "./util";
import drawMethod from "./draw";
import { changeRadar } from "@/api/apra"
import WKT from 'ol/format/WKT';
import VectorSource from 'ol/source/Vector';
import { Fill, Stroke, Style } from 'ol/style';
import VectorLayer from 'ol/layer/Vector';
import { getinitArpa } from "@/api/apra";

export default {
  methods: {
    // 刷新船舶样式
    refreshShipStyle(layer = this.shipLayer) {
      // 清空船舶样式
      layer.getSource().getFeatures().forEach((feature) => {
        layer.getSource().removeFeature(feature);
      });
      // 清空船舶辅助功能样式
      // this.shipStyleLayer.getSource().getFeatures().forEach((feature) => {
      //   this.shipStyleLayer.getSource().removeFeature(feature);
      // });
      // 重新开始绘制
      for (let item of this.ShipList) {
        this.handleDrawShip(item)
      }
    },
    refreshOtherShipStyle(layer = this.otherShipLayer) {
      layer.getSource().getFeatures().forEach((feature) => {
        layer.getSource().removeFeature(feature);
      });
      for (let item of this.OtherShipList) {
        this.handleDrawOtherShip(item)
      }
    },
    // 船舶点击事件
    shipOnClick(feature) {
      // 船舶红边
      const typeObj = {
        1: "handleDrawShipByMmsi",
        2: "handleDrawOtherShipMmsi"
      }
      const oldData = this.selectShipData;
      const newData = Object.assign({}, feature.values_.detail, {
        styleType: feature.get('shipType')
      });
      this.selectShipData = newData
      // 更新当前选中状态
      if (oldData.mmsi) {
        this[typeObj[oldData.styleType]](oldData.mmsi, false)
      }
      this[typeObj[feature.get('shipType')]](newData.mmsi, true)
      // 显示船舶详细信息
      this.handleShipDetail(newData)
    },
    // 船舶点击事件 - 新
    shipOnclickFn(feature) {
      const data = feature.values_.detail
      console.log("detail: ", data.targetNum)
      this.$set(this, "shipDetailInfo", data)
      this.$refs.detail.open(data)
    },
    handleDrawShipByMmsi(mmsi, state) {
      const row = this.shipSource.getFeatureById(mmsi).values_.detail
      row.isSelect = state
      this.handleDrawShip(row)
    },
    handleDrawOtherShipMmsi(mmsi, state) {
      const row = this.otherShipSource.getFeatureById(mmsi).values_.detail
      row.isSelect = state
      this.handleDrawOtherShip(row)
    },
    // 显示船舶详情
    handleShipDetail(row) {
      row.endPort = row.destination || row.endPort
      this.$refs.shipDetail.open(row)
      this.$set(this, "shipDetailInfo", row)
      // 船舶选中样式
      // this.drawCheckBox(row)
      // 开启船舶追踪
      this.isTracking = true;
    },
    // 船舶进入报警
    setAlarmList(alarmList) {
      // 改变船舶显示样式
      for (let item of alarmList) {
        // 首先判断报警的类型，0 解除报警 1 新增报警
        var shipFeature = this.shipSource.getFeatureById(item.mmsi);
        let detail = shipFeature.values_.detail;
        if (item.status === 0) {
          // 判断船舶中是否已经有报警信息，有则去除
          if (detail.alarmList) {
            // 如果有报警信息，遍历获取相同的报警信息，并去除
            const index = detail.alarmList.findIndex(m => m.abnormalId === item.abnormalId)
            if (index >= 0) {
              detail.alarmList.splice(index, 1)
            }
            // 判断船舶是否还有报警信息
            if (detail.alarmList.length === 0) {
              delete detail.alarmList
            }
            // 重新绘制船舶
            this.handleDrawShip(detail)
          }
        } else {
          // 判断船舶是否已经存在这个报警信息
          if (detail.alarmList) {
            // 没有就加上
            const index = detail.alarmList.findIndex(m => m.abnormalId === item.abnormalId)
            if (index === -1) {
              detail.alarmList.push(item)
              // 重新绘制船舶
              this.handleDrawShip(detail)
            }
          } else {
            detail.alarmList = [item]
            // 重新绘制船舶
            this.handleDrawShip(detail)
          }
        }
      }
    },
    // 点击侧边栏显示船舶
    handleShowShipBySearch(row) {
      // 首先找到船舶在地图上的位置，将地图的中心点转移到船舶所在地
      // 然后弹出详情框，注意：列表中的信息不是全的，需要取到地图中船舶的信息
      const data = this.shipSource.getFeatureById(row.mmsi)
      if (data) {
        row = Object.assign(row, data.values_.detail)
        moveToCenterByLonAndLat([row.longitude, row.latitude], this.map)
        this.shipOnClick(data)
      } else {
        this.$refs.shipDetail.open(row)
        this.$set(this, "shipDetailInfo", row)
      }
    },
    // 船舶追踪
    shipTracking(row) {
      var to = transformLonlatToNow([row.longitude, row.latitude]);
      var view = this.map.getView();
      // 设置地图等级
      view.animate({
        center: to,
        duration: 0
      });
      // fullyAutomatic
    },
    // 查看mob信息
    openMobDetail(row) {
      this.$refs.MobDetail.open(row)
    },
    refreshMobList(data) {
      this.$refs.float.opeartDetail(data, "MOBWarning")
      this.$refs.float.computeNumber("MOBWarning", data.filter(m => m.status === '0').length)
    },
    // 显示雷达内船舶移动的动画
    showShipLine(list = this.trajectorysList) {
      this.trajectorysList = list
      drawMethod.drawShipTrajectorys(this.map, list);
      this.trajectorysShow = true;
    },
    showLineById(data) {
      drawMethod.drawShipTrajectorys(this.map, data);
    },
    closeShipLine() {
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === "TRAJECTORY");
      if (layerTmp) {
        this.map.removeLayer(layerTmp)
      }
      this.trajectorysShow = true;
    },
    handleShowVideo() {
      if (this.buttonShow.video) {
        this.handleCloseVideo()
      } else {
        // 先关掉航线
        if (this.buttonShow.line) {
          this.handleCloseLine()
        }
        // 打开CCTV
        this.buttonShow.video = true;
        this.$nextTick(() => {
          this.$refs.video.open()
        })
      }
    },
    handleCloseVideo() {
      this.buttonShow.video = false
      this.$refs.video.flv_destroy()
    },
    handleShowLine() {
      if (this.buttonShow.line) {
        this.handleCloseLine()
      } else {
        if (this.buttonShow.video) {
          this.handleCloseVideo()
        }
        this.buttonShow.line = true;
      }
    },
    handleCloseLine() {
      this.buttonShow.line = false;
      this.closeShipLine()
    },
    // 控制雷达
    changeRadar() {
      changeRadar(this.radarControlData).then(() => { })
    },
    // 控制摄像头
    radarControlType(type) {
      let form = this.radarControlData;
      changeRadar({ ...form, controlTypeEnum: type }).then(() => { })
    },
    // 船舶追踪
    radarShipTracking(num, state) {
      if (!state) {
        changeRadar(this.radarControlData).then(() => { })
      } else {
        let form = { ...this.radarControlData }
        form.targetNum = num
        changeRadar(form).then(() => { })
      }
    },
    // 控制图层显隐
    changeWaveRadar() {
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === this.radarLayerName)
      if (this.radarShowOptions.waveShow === 0) {
        if (layerTmp) layerTmp.setVisible(false);
      } else {
        if (layerTmp) layerTmp.setVisible(true);
      }
    },
    // 播放视频
    handleVideo(data) {
      let form = { ...this.radarControlData };
      form.targetNum = data.targetNum
      changeRadar(form).then(() => { })
      // 先关掉航线
      if (this.buttonShow.line) {
        this.handleCloseLine()
      }
      if (!this.buttonShow.video) {
        this.buttonShow.video = true;
        // 打开CCTV
        this.buttonShow.video = true;
        this.$nextTick(() => {
          this.$refs.video.open()
        })
      }
      this.$nextTick(() => {
        this.$refs.video.showShip(data.info, 1)
      })
    },
    // 绘制禁射区
    drawForbiddenAreas(point = this.apraList[0]) {
      const typhoonStyleFn = () => {
        return new Style({
          fill: new Fill({
            color: "rgba(216, 210, 67, 0.7)"
          }),
          stroke: new Stroke({
            color: "rgba(216, 210, 67, 1)",
            width: 2
          }),
        });
      }
      // 绘制风圈
      const getPolygonFeature = (point) => {
        var wktformat = new WKT();
        const lonlat = transformLonlatToNow([point.lon, point.lat])
        var wkt = "POLYGON((";
        var wkt0 = "", _interval = 1;
        // 计算角度
        const jisuan = (a) => {
          let b = 0
          if (a <= 90) {
            b = 90 - a
          } else {
            b = 450 - a
          }
          return b
        }
        for (var i = 0; i < 360 / _interval; i++) {
          var _r = 0;
          var _ang = i * _interval;
          // if (_ang >= 0 && _ang <= 135) {
          //   _r = getRadius(point.maxLength * 1852, this.map);
          // }
          for (let item of point.info.forbiddenAreas) {
            if (item.isOpen === 1) {
              if (_ang <= jisuan(item.startCog) || _ang >= jisuan(item.endCog)) {
                _r = getRadius(point.maxLength * 1852, this.map);
              }
            }
          }
          var x = lonlat[0] + _r * Math.cos(_ang * 3.14 / 180);
          var y = lonlat[1] + _r * Math.sin(_ang * 3.14 / 180);

          wkt = wkt + "" + x + " " + y + ", ";
          if (i === 0) {
            wkt0 = "" + x + " " + y + "";
          }
        }
        wkt = wkt + wkt0 + "))";
        let feature = wktformat.readFeature(wkt)
        feature.setProperties()
        return feature
      }
      let areaFeature = getPolygonFeature(point)
      console.log("禁射区: ", areaFeature)
      // 添加图层
      let source = new VectorSource({
        features: null
      })
      let layerTmp = new VectorLayer({
        source: source,
        zIndex: 201,
        name: "forbiddenAreas",
        style: typhoonStyleFn
      });
      source.addFeature(areaFeature)
      this.map.addLayer(layerTmp)
    },
    // 改变船舶显示的类型
    changeShip() {
      // 清空现在所有的船
      let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === "SHIPLAYER")
      if (layerTmp) this.map.removeLayer(layerTmp)
      this.initShipTeam()
      getinitArpa().then(({ data }) => {
        for (let item of data) {
          if (this.shipShowType === 0) {
            this.shipShow0(item)
          } else if (this.shipShowType === 1) {
            this.shipShow1(item)
          } else if (this.shipShowType === 2) {
            this.shipShow2(item)
          } else if (this.shipShowType === 3) {
            this.shipShow3(item)
          } else {
            this.shipShow(item)
          }
        }
      })
    }
  }
}
